package cn.edu.cimv.service.impl;

import cn.edu.cimv.dao.entity.Cata;
import cn.edu.cimv.dao.entity.Menu;
import cn.edu.cimv.dao.mapper.ContentMapper;
import cn.edu.cimv.pojo.Catalogue;
import cn.edu.cimv.pojo.Page;
import cn.edu.cimv.service.ContentService;
import cn.edu.cimv.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by 门铎 on 2016/6/24.
 */
@Service
public class ContentServiceImpl implements ContentService {
    @Autowired
    private ContentMapper contentMapper;

    /**
     * 根据url 查找单页面表是否有记录
     * @param name
     * @return
     */
    @Override
    public int checkCataIsExisting(String name) {
        //根据name 找到id
        name = "single/" + name;
        String id = contentMapper.getMenuId(name);
        //根据id 查找单页面表是否有记录
        int count = contentMapper.checkContent(id);
        return count;
    }

    @Override
    public Cata getCata(String name) {
        //根据name 找到id
        name = "single/" + name;
        String id = contentMapper.getMenuId(name);
        return contentMapper.getCata(id);
    }

    @Override
    public Menu getMenu(String name) {
        return contentMapper.getMenuIdName("single/" + name);
    }

    @Override
    public void newCata(String name,String content) {
        Menu menu = getMenu(name);
        Cata cata = new Cata();
        cata.setSingleId(menu.getMenuId());
        cata.setSingleName(menu.getMenuName());
        cata.setContent(content);
        cata.setUpdateTime(DateUtil.toDateString(new Date()));
        contentMapper.insertContent(cata);
    }

    @Override
    public void updateCata(String name, String content) {
        Menu menu = getMenu(name);
        Cata cata = new Cata();
        cata.setSingleId(menu.getMenuId());
        cata.setSingleName(menu.getMenuName());
        cata.setContent(content);
        cata.setUpdateTime(DateUtil.toDateString(new Date()));
        contentMapper.updateContent(cata);
    }

    @Override
    public Map<Integer,List<Menu>> getMenuList(String roleId) {
        List<Menu> menuList = contentMapper.getMenuList(roleId);
        Map<Integer,List<Menu>> menuMap = new HashMap<>();
        for (Menu m:menuList) {
            if(menuMap.containsKey(m.getMenuLevel())){
                menuMap.get(m.getMenuLevel()).add(m);
            }else{
                List<Menu> subList = new ArrayList<>();
                subList.add(m);
                menuMap.put(m.getMenuLevel(),subList);
            }
        }
        return menuMap;
    }
}
